package com.coder520.sync_learning.demo;

import java.util.Map.Entry;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.prefs.BackingStoreException;

public class BankWaterService implements Runnable{
	
	private CyclicBarrier c=new CyclicBarrier(4, this);
	
	private Executor executor=Executors.newFixedThreadPool(4);
	
	private ConcurrentHashMap<String, Integer> sheet=new ConcurrentHashMap<String, Integer>();
	
	private void count() {
		// TODO Auto-generated method stub
		for (int i = 0; i < 4; i++) {
			executor.execute(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					sheet.put(Thread.currentThread().getName(), 1);
					try {
						c.await();
					} catch (InterruptedException|BrokenBarrierException e) {
						e.printStackTrace();
					}
				}
			});
		}

	}
	
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		int result=0;
//		汇总每个sheet计算出的结果
		for (Entry<String, Integer> sheets:sheet.entrySet()) {
			result+=sheets.getValue();
			System.out.println(sheets.getValue());
		}
		
		sheet.put("result", result);
//		System.out.println(sheet.size());
//		System.out.println(result);
	}
	
	
	public static void main(String[] args) {
		BankWaterService bankWaterService=new BankWaterService();
		bankWaterService.count();
	}
}
